package com.evernote.dao;

import java.nio.channels.ClosedByInterruptException;
import java.sql.SQLException;

import com.evernote.db.DBUtil;
import com.evernote.entity.User;

/**
 * 用户 dao类
 * @author zhou
 *
 */
public class UserDao extends BaseDao {
	
	/**
	 * 查询用户是否存在
	 * @param u
	 * @return true 存在，false 不存在
	 */
	public boolean isExist(User u) {
		boolean flag = false;
		try {
			int count = 0;
			connection = DBUtil.getConnection();
			String sql = "select count(*) as count from user where username = ?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, u.getUsername());
			resultSet = preparedStatement.executeQuery();
			while(resultSet.next()) {
				count = resultSet.getInt("count");
			}
			if(count != 0) {
				flag = true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closed();
		}
		return flag;
	}
	
	/**
	 * 添加用户
	 * @param u
	 * @return 返回数据库修改条数 0失败 1成功
	 */
	public int addUser(User u) {
		int count = 0;
		try {
			connection = DBUtil.getConnection();
			String sql = "insert into user(username, password) values(?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, u.getUsername());
			preparedStatement.setString(2, u.getPassword());
			count = preparedStatement.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closed();
		}
		return count;
	}
	
	/**
	 * 根据用户名查询id
	 * @param u
	 * @return
	 */
	public int findIdByUsername(User u) {
		int id = 0;
		try {
			connection = DBUtil.getConnection();
			String sql = "select id from user where username = ?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, u.getUsername());
			resultSet = preparedStatement.executeQuery();
			while(resultSet.next()) {
				id = resultSet.getInt("id");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closed();
		}
		return id;
	}
	
	/**
	 * 登录
	 * @param u
	 * @return 成功将返回用户的id 失败返回0
	 */
	public int login(User u) {
		int id = 0;
		try {
			connection = DBUtil.getConnection();
			String sql = "select id from user where username = ? and password = ?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, u.getUsername());
			preparedStatement.setString(2, u.getPassword());
			resultSet = preparedStatement.executeQuery();
			while(resultSet.next()) {
				id = resultSet.getInt("id");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closed();
		}
		return id;
	}
	
}
